package simpledb;

import java.io.Serializable;
import java.util.*;

import static simpledb.Type.*;

/**
 * TupleDesc describes the schema of a tuple.
 * 元组描述器
 * 存储每个元组的字段类型和字段名称
 */
public class TupleDesc implements Serializable {

    private int numFields;

    private TDItem[] tdItems;
    /**
     * A help class to facilitate organizing the information of each field
     * 静态内部类，表示元组描述其的内部对象，存储元组每个属性的类型和名称
     * */
    public static class TDItem implements Serializable {

        private static final long serialVersionUID = 1L;

        /**
         * The type of the field
         * */
        public final Type fieldType;
        
        /**
         * The name of the field
         * */
        public final String fieldName;

        public TDItem(Type t, String n) {
            this.fieldName = n;
            this.fieldType = t;
        }

        public String toString() {
            return fieldName + "(" + fieldType + ")";
        }
    }

    /**
     * @return
     *        An iterator which iterates over all the field TDItems
     *        that are included in this TupleDesc
     * */
    public Iterator<TDItem> iterator() {
        // some code goes here
        return Arrays.stream(tdItems).iterator();
    }

    private static final long serialVersionUID = 1L;

    /**
     * Create a new TupleDesc with typeAr.length fields with fields of the
     * specified types, with associated named fields.
     * 
     * @param typeAr
     *            array specifying the number of and types of fields in this
     *            TupleDesc. It must contain at least one entry.
     * @param fieldAr
     *            array specifying the names of the fields. Note that names may
     *            be null.
     */
    public TupleDesc(Type[] typeAr, String[] fieldAr) {
        // some code goes here
        int typeAr_len = typeAr.length;
        int fieldAr_len = fieldAr.length;
        if(typeAr_len!=fieldAr_len)
            throw new RuntimeException();
        numFields = typeAr.length;
        tdItems = new TDItem[typeAr_len];
        for (int i = 0; i < typeAr_len; i++) {
            tdItems[i] = new TDItem(typeAr[i],fieldAr[i]);
        }
    }

    /**
     * Constructor. Create a new tuple desc with typeAr.length fields with
     * fields of the specified types, with anonymous (unnamed) fields.
     * 
     * @param typeAr
     *            array specifying the number of and types of fields in this
     *            TupleDesc. It must contain at least one entry.
     */
    public TupleDesc(Type[] typeAr) {
        // some code goes here
        this(typeAr,new String[typeAr.length]);
        numFields = typeAr.length;
    }

    public TupleDesc(int numFields, TDItem[] tdItems) {
        this.numFields = numFields;
        this.tdItems = tdItems;
    }

    /**
     * @return the number of fields in this TupleDesc
     */
    public int numFields() {
        // some code goes here
        return numFields;
    }

    public int numTypes() {

        return tdItems.length;
    }
    /**
     * Gets the (possibly null) field name of the ith field of this TupleDesc.
     * 
     * @param i
     *            index of the field name to return. It must be a valid index.
     * @return the name of the ith field
     * @throws NoSuchElementException
     *             if i is not a valid field reference.
     */
    public String getFieldName(int i) throws NoSuchElementException {
        // some code goes here
        return tdItems[i].fieldName;
    }

    /**
     * Gets the type of the ith field of this TupleDesc.
     * 
     * @param i
     *            The index of the field to get the type of. It must be a valid
     *            index.
     * @return the type of the ith field
     * @throws NoSuchElementException
     *             if i is not a valid field reference.
     */
    public Type getFieldType(int i) throws NoSuchElementException {
        // some code goes here
        if(i<tdItems.length)
            return tdItems[i].fieldType;
        throw new NoSuchElementException();
    }

    /**
     * Find the index of the field with a given name.
     * 
     * @param name
     *            name of the field.
     * @return the index of the field that is first to have the given name.
     * @throws NoSuchElementException
     *             if no field with a matching name is found.
     */
    public int fieldNameToIndex(String name) throws NoSuchElementException {
        if(name==null)
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder(name);
        int index = name.indexOf('.');
        if(index!=-1)
        {
            sb.deleteCharAt(index);
        }
        for (int i = 0; i < tdItems.length; i++) {
            if(tdItems[i].fieldName.equals(sb.toString()))
            {
                return i;
            }
        }
        throw new NoSuchElementException();
    }

    /**
     * @return The size (in bytes) of tuples corresponding to this TupleDesc.
     *         Note that tuples from a given TupleDesc are of a fixed size.
     */
    public int getSize() {
        // some code goes here
        int size = 0;
        for(TDItem tdItem:tdItems)
        {
            if(tdItem.fieldType == INT_TYPE)
                size+=INT_TYPE.getLen();
            else if(tdItem.fieldType == STRING_TYPE)
                size+=STRING_TYPE.getLen();
        }
        return size;
    }

    /**
     * Merge two TupleDescs into one, with td1.numFields + td2.numFields fields,
     * with the first td1.numFields coming from td1 and the remaining from td2.
     * 
     * @param td1
     *            The TupleDesc with the first fields of the new TupleDesc
     * @param td2
     *            The TupleDesc with the last fields of the TupleDesc
     * @return the new TupleDesc
     */
    public static TupleDesc merge(TupleDesc td1, TupleDesc td2) {
        // some code goes here
        int td1_len = td1.numFields();
        int td2_len = td2.numFields();
        int len = td1_len+td2_len;
        TDItem[] tdItems = new TDItem[len];
        for (int i = 0; i < td1_len; i++) {
            tdItems[i] = new TDItem(td1.getFieldType(i),td1.getFieldName(i));
        }
        for (int i = td1_len; i < len; i++) {
            tdItems[i] = new TDItem(td2.getFieldType(i-td1_len),td2.getFieldName(i-td1_len));
        }
        TupleDesc td = new TupleDesc(len,tdItems);
        return td;
    }

    /**
     * Compares the specified object with this TupleDesc for equality. Two
     * TupleDescs are considered equal if they have the same number of items
     * and if the i-th type in this TupleDesc is equal to the i-th type in o
     * for every i.
     * 
     * @param o
     *            the Object to be compared for equality with this TupleDesc.
     * @return true if the object is equal to this TupleDesc.
     */

    public boolean equals(Object o) {
        if(null==o)
            return false;
        // some code goes here
        if(!(o instanceof TupleDesc))
        {
            return false;
        }
        TupleDesc td1 = (TupleDesc)o;
        if(numTypes()!=td1.numTypes())
            return false;
        for (int i = 0; i < td1.numTypes(); i++) {
            if(tdItems[i].fieldType!=td1.getFieldType(i))
                return false;
        }
        return true;
    }

    public int hashCode() {
        // If you want to use TupleDesc as keys for HashMap, implement this so
        // that equal objects have equals hashCode() results
        throw new UnsupportedOperationException("unimplemented");
    }

    /**
     * Returns a String describing this descriptor. It should be of the form
     * "fieldType[0](fieldName[0]), ..., fieldType[M](fieldName[M])", although
     * the exact format does not matter.
     * 
     * @return String describing this descriptor.
     */
    public String toString() {
        // some code goes here
        return "";
    }
}
